package org.ccay.validator;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.ccay.core.exception.IFriendlyMessage;
import org.ccay.core.exception.SystemException;
import org.ccay.core.log.ILogger;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.util.JsonUtil;

/**
 * Validator SystemException
 * 
 * 用户不可理解的异常以此异常或子类的形式抛出 
 * 
 * @author chaowangbang
 *
 */
public class ValidatorSystemException extends SystemException implements IFriendlyMessage {

	/** Auto-generated serialization id */
	private static final long serialVersionUID = -4081089107203456518L;

	/** 日志类 */
	private final ILogger logger = CcayLoggerFactory.getLogger(ValidatorSystemException.class);
			
	/** action验证信息 */
	private Collection<ValidationMessage> actionErrors;
	
	private Collection<ValidationMessage> fieldErrors;

	/**
	 * @param errorCode
	 */
	public ValidatorSystemException(String errorCode){
		super(errorCode);
	}

	/**
	 * @param errorCode
	 */
	public ValidatorSystemException(String errorCode,Throwable innerException){
		super(errorCode,innerException);
	}
	/**
	 * @return
	 */
	public Collection<ValidationMessage> getActionErrors() {
		return actionErrors;
	}

	/**
	 * @param actionErrors
	 */
	public void setActionErrors(Collection<ValidationMessage> actionErrors) {
		this.actionErrors = actionErrors;
	}

	/**
	 * @return
	 */
	public Collection<ValidationMessage> getFieldErrors() {
		return fieldErrors;
	}

	/**
	 * @param fieldErrors
	 */
	public void setFieldErrors(Collection<ValidationMessage> fieldErrors) {
		this.fieldErrors = fieldErrors;
	}
	
	public boolean hasFieldErrors() {
		return this.fieldErrors!=null && !this.fieldErrors.isEmpty();
	}
	
	public boolean hasFieldError(String fieldName) {
		if(hasFieldErrors()) {
			Iterator<ValidationMessage> errors = this.fieldErrors.iterator();
			while(errors.hasNext()) {
				FieldValidationMessage message = (FieldValidationMessage)errors.next();
				if(message.getFieldName()!=null && message.getFieldName().equals(fieldName)) {
					return true;
				}
			}
		}
		
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getMessage() {
		try {
			//将验证信息用json格式返回
			Map messageMap = new HashMap();
			//action验证信息
			messageMap.put("actionErrors", actionErrors);
			//字段验证信息
			messageMap.put("fieldErrors", fieldErrors);
			return JsonUtil.getJsonString(messageMap);
		} catch (IOException e) {
			//如果发生异常，则调用super.getMessage()，并记录日志
			logger.error(e);
			return super.getMessage();
		}
	}
	
}
